﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using MySql.Data;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using MySql.Data.MySqlClient;

namespace TankServer.Core
{
    class DataMgr
    {
        MySqlConnection sqlConn;

        public static DataMgr instance;
        public DataMgr()
        {
            instance = this;
            //连接数据库
            Connect();
        }

        public void Connect()
        {
            Console.WriteLine("Connect...");
            string connStr = "Database=game;DataSource=127.0.0.1;SslMode=none;";
            connStr += "User Id=root;port=3306;";
            sqlConn = new MySqlConnection(connStr);
            try
            {
                sqlConn.Open();
                Console.WriteLine("[DataMgr]Connected!");
            }
            catch(Exception e)
            {
                Console.WriteLine("[DataMgr]Connect:"+e.Message);
            }
        }

        private bool CanRegister(string id)
        {
            string cmdStr = string.Format("select * from user where id='{0}';",id);
            MySqlCommand cmd = new MySqlCommand(cmdStr,sqlConn);
            try
            {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                bool hasRows = dataReader.HasRows;
                dataReader.Close();
                return !hasRows;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]CanRegister:"+e.Message);
                return false;
            }

        }


        //注册
        public bool Register(string id,string pw)
        {
            if (!CanRegister(id))
            {
                Console.WriteLine("[DataMgr]Register:ID重名，不能注册!");
                return false;
            }
            string cmdStr = string.Format("insert into user set id='{0}',pw='{1}';",id,pw);
            MySqlCommand cmd = new MySqlCommand(cmdStr,sqlConn);
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]Register:"+e.Message);
                return false;
            }
        }

        //创建角色
        public bool CreatePlayer(string id)
        {
            //序列化
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            PlayerData playerData = new PlayerData();
            try
            {
                formatter.Serialize(stream,playerData);
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]CreatePlayer 序列化"+e.Message);
                return false;
            }
            byte[] byteArr = stream.ToArray();

            string cmdStr = string.Format("insert into player set id='{0}',data=@data;",id);
            MySqlCommand cmd = new MySqlCommand(cmdStr,sqlConn);
            cmd.Parameters.Add("@data",MySqlDbType.Blob);
            cmd.Parameters[0].Value = byteArr;

            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]CreatePlayer 写入"+e.Message);
                return false;
            }
        }

        //检测用户名和密码
        public bool CheckPassWord(string id,string pw)
        {
            string cmdStr = string.Format("select * from user where id='{0}' and pw='{1}';",id,pw);
            MySqlCommand cmd = new MySqlCommand(cmdStr,sqlConn);
            try
            {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                bool hasRows = dataReader.HasRows;
                dataReader.Close();
                return hasRows;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]CheckPassWord:"+e.Message);
                return false;
            }
        }

        //获取玩家数据
        public PlayerData GetPlayerData(string id)
        {
            PlayerData playerData = null;
            string cmdStr = string.Format("select * from player where id='{0}';",id);
            MySqlCommand cmd = new MySqlCommand(cmdStr,sqlConn);
            byte[] buffer = new byte[1];
            try
            {
                MySqlDataReader dataReader = cmd.ExecuteReader();
                if (!dataReader.HasRows)
                {
                    dataReader.Close();
                    return playerData;
                }
                dataReader.Read();
                long len = dataReader.GetBytes(1,0,null,0,0);
                buffer = new byte[len];
                dataReader.GetBytes(1,0,buffer,0,(int)len);
                dataReader.Close();
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]GetPlayerData 查询"+e.Message);
                return playerData;
            }
            //反序列化
            MemoryStream stream = new MemoryStream(buffer);
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                playerData = (PlayerData)formatter.Deserialize(stream);
                return playerData;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]GetPlayerData 反序列化 "+e.Message);
                return playerData;
            }
        }

        //保存数据
        public bool SavePlayer(Player player)
        {
            string id = player.id;
            PlayerData playerData = player.data;
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            try
            {
                formatter.Serialize(stream,playerData);
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]SavePlayer 序列化 "+e.Message);
                return false;
            }
            byte[] bytes = stream.ToArray();
            string fomatStr = "update player set data=@data where id='{0}';";
            string cmdstr = string.Format(fomatStr,player.id);
            MySqlCommand cmd = new MySqlCommand(cmdstr,sqlConn);
            cmd.Parameters.Add("@data",MySqlDbType.Blob);
            cmd.Parameters[0].Value = bytes;
            try
            {
                cmd.ExecuteNonQuery();
                return true;
            }catch(Exception e)
            {
                Console.WriteLine("[DataMgr]SavePlayer 序列化 "+e.Message);
                return false;
            }
        }


    }
}
